package cn._2vin.user.bingxuexiehuione.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.omg.CORBA.PRIVATE_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import cn._2vin.user.bean.ImgUrl;
import cn._2vin.user.bean.LianxiFood;
import cn._2vin.user.bingxuexiehuione.service.HomePageMeiShiService;
import cn._2vin.user.bingxuexiehuione.service.ImgUrlService;
import cn._2vin.user.utils.FileUtils;

@Controller
@RequestMapping("user/userinformation/*")
public class UserinformationController {

	@Autowired
	private ImgUrlService imgUrlService;
	@Autowired
	private HomePageMeiShiService homePageMeiShiService;

	@RequestMapping("information.do")
	public String information() {
		return "users/Userinformationinput";

	}

	@RequestMapping("hh.do")
	public String hh(HttpServletRequest request, Model model,HttpServletResponse response) throws IOException {
		String username = request.getParameter("username");
		//username=new String(username.getBytes("ISO-8859-1"),"UTF-8");
		model.addAttribute("username", username);
		return "users/upload";

	}
	/*
	 * 商家信息录入
	 */

	@RequestMapping("informationinput.do")
	@ResponseBody
	public ModelAndView informationinput(@RequestParam("myfiles") MultipartFile[] files,
			HttpServletRequest request, HttpServletResponse response,
			Model model) throws ServletException, IOException {
		String username = request.getParameter("username");
		List<LianxiFood> lianxiFoods = homePageMeiShiService.selectusername(username);
		try {
		if (lianxiFoods.size()<=0 && username.length()>0) {
				String homeImgUrl = request.getParameter("homeImgUrl");
				String userclassname = request.getParameter("userclassname");
				String userclassid = request.getParameter("userclassid");
				String usertext = request.getParameter("usertext");
				String foodtext = request.getParameter("foodtext");
				String longitude = request.getParameter("longitude");
				String latitude = request.getParameter("latitude");
				String cityname = request.getParameter("cityname");
				String cityid = request.getParameter("cityid");
				String foodname = request.getParameter("foodname");
				String starlevel = request.getParameter("starlevel");
				String percapitaprice = request.getParameter("percapitaprice");
				String phone = request.getParameter("phone");
				String cmspassword = request.getParameter("cmspassword");
				String videourl = request.getParameter("videourl");
				// String businessimgurl=request.getParameter("businessimgurl");
				String commentid = request.getParameter("commentid");
				String discountid = request.getParameter("discountid");
				String businesshours = request.getParameter("businesshours");

				String openid = request.getParameter("openid");
				String closingtimees = request.getParameter("closingtimees");
				String wifi = request.getParameter("wifi");
				String cmsname = request.getParameter("cmsname");
				String videoimgurl = request.getParameter("videoimgurl");
				Date n_date = new Date();
				Date update_date = new Date();
				String detailedaddress = request
						.getParameter("detailedaddress");
				String Headportraiturl = request
						.getParameter("Headportraiturl");
				String bank_name = request
						.getParameter("bank_name");
				String bank_no = request
						.getParameter("bank_no");
				String contact = request
						.getParameter("contact");
				String address = request
						.getParameter("address");
				String user_id = request
						.getParameter("user_id");

				if (files != null && files.length > 0) {
					for (int i = 0; i < files.length; i++) {
						MultipartFile file = files[i];
						CommonsMultipartFile cf = (CommonsMultipartFile) file;
						DiskFileItem fi = (DiskFileItem) cf.getFileItem();
						File f1 = fi.getStoreLocation();
						URL url = FileUtils.picCOS(f1);
						String urlString = url.toString();
						
						String[] urlArray = urlString.split("[?]",1000);
						
						String urlBase = "";
						String requery = "";//参数
						if(urlArray.length > 0){
							urlBase = urlArray[0];
							if(urlArray.length > 1){
								requery =  urlArray[1];
							}
						}
						if (i==0) {
						  homeImgUrl=urlBase;
						}
						if (i==1) {
							Headportraiturl=urlBase;	
						}
						if (i==2) {
							videoimgurl=urlBase;
						}
				
					}
				}
				LianxiFood lianxiFood = new LianxiFood();
				if (businesshours!=null) {
					lianxiFood.setBusinesshours(businesshours);
				}
				if (cityid!=null) {
					lianxiFood.setCityid(cityid);
				}
				if (cityname!=null) {
					lianxiFood.setCityname(cityname);
				}
				if (closingtimees!=null) {
					lianxiFood.setClosingtimees(closingtimees);
				}
				if (cmsname!=null) {
					lianxiFood.setCmsname(cmsname);
				}
				if (cmspassword!=null) {
					lianxiFood.setCmspassword(cmspassword);
				}
				if (commentid!=null) {
					lianxiFood.setCommentid(commentid);
				}
				if (discountid!=null) {
					lianxiFood.setDiscountid(discountid);
				}
				if (businesshours!=null) {
					lianxiFood.setFoodname(foodname);
				}
				if (foodtext!=null) {
					lianxiFood.setFoodtext(foodtext);
				}
				if (homeImgUrl!=null) {
					lianxiFood.setHomeImgUrl(homeImgUrl);
				}
				if (latitude!=null) {
					lianxiFood.setLatitude(latitude);
				}
				if (longitude!=null) {
					lianxiFood.setLongitude(longitude);
				}
				if (n_date!=null) {
					lianxiFood.setN_date(n_date);
				}
				if (openid!=null) {
					lianxiFood.setOpenid(openid);
				}
				if (percapitaprice!=null) {
					lianxiFood.setPercapitaprice(percapitaprice);
				}
				if (phone!=null) {
					lianxiFood.setPhone(phone);
				}
				if (starlevel!=null) {
					lianxiFood.setStarlevel(starlevel);
				}
				if (update_date!=null) {
					lianxiFood.setUpdate_date(update_date);
				}
				if (userclassid!=null) {
					lianxiFood.setUserclassid(userclassid);
				}
				if (userclassname!=null) {
					lianxiFood.setUserclassname(userclassname);
				}
				if (username!=null) {
					lianxiFood.setUsername(username);
				}
				if (usertext!=null) {
					lianxiFood.setUsertext(usertext);
				}
				if (videoimgurl!=null) {
					lianxiFood.setVideoimgurl(videoimgurl);
				}
				if (videourl!=null) {
					lianxiFood.setVideourl(videourl);
				}
				if (wifi!=null) {
					lianxiFood.setWifi(wifi);
				}
//				if (businesshours!=null) {
//					lianxiFood.setBusinesshours(businesshours);
//				}
				if (detailedaddress!=null) {
					lianxiFood.setDetailedaddress(detailedaddress);
				}
				if (Headportraiturl!=null) {
					lianxiFood.setHeadportraiturl(Headportraiturl);
				}
				if (bank_name!=null) {
					lianxiFood.setBank_name(bank_name);
				}
				if (bank_no!=null) {
					lianxiFood.setBank_no(bank_no);
				}
				if (contact!=null) {
					lianxiFood.setContact(contact);
				}
				if (address!=null) {
					lianxiFood.setAddress(address);
				}

				homePageMeiShiService.insert(lianxiFood);

				model.addAttribute("username", username);
				

		} else {
			ModelAndView mnv = new ModelAndView(new RedirectView(
					request.getContextPath()
							+ "/user/userinformation/information.do"));
			return mnv;
		}
		
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ModelAndView mnv = new ModelAndView(new RedirectView(
					request.getContextPath()
							+ "/user/userinformation/information.do"));
			return mnv;
		}
		ModelAndView mnv = new ModelAndView();	
		mnv.setViewName("users/upload");
		return mnv;

	}

	@RequestMapping("filesUpload.do")
	// requestParam要写才知道是前台的那个数组
	public ModelAndView filesUpload(
			@RequestParam("myfile") MultipartFile[] files,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String username = request.getParameter("username");
		List<String> list = new ArrayList<String>();
		try {
		
		if (files != null && files.length > 0) {
			for (int i = 0; i < files.length; i++) {
				MultipartFile file = files[i];
				CommonsMultipartFile cf = (CommonsMultipartFile) file;
				DiskFileItem fi = (DiskFileItem) cf.getFileItem();
				File f1 = fi.getStoreLocation();
				URL url = FileUtils.picCOS(f1);
				String urlString = url.toString();
				
				String[] urlArray = urlString.split("[?]",1000);
				
				String urlBase = "";
				String requery = "";//参数
				if(urlArray.length > 0){
					urlBase = urlArray[0];
					if(urlArray.length > 1){
						requery =  urlArray[1];
					}
				}
				
				String urlString2=urlBase;
				
				Date newdate = new Date();
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				try {
					newdate=df.parse((String)request.getParameter("newdate"));
				} catch (Exception e) {
					// TODO: handle exception
				}
				ImgUrl imgUrl = new ImgUrl();
				imgUrl.setImgurl(urlString2);
				imgUrl.setUsername(username);
				imgUrl.setNewdate(newdate);

				imgUrlService.insert(imgUrl);
		
			}
		}
		
		} catch (Exception e) {
			// TODO: handle exception
		}
		List<ImgUrl> listimg = imgUrlService.selectlistImgUrl(username);
		String id=listimg.get(0).getId();
		ModelAndView mnv = new ModelAndView(new RedirectView(
				request.getContextPath()
						+ "/user/userinformation/jsons.do?id=" + id
						+ ""));
		return mnv;
	}
	
//	String[] str1 = { "J", "a", "v", "a", "中" }; 
//	String[] str2 = { "如", "何", "把", "两", "个", "数", "组", "合", "并", "为", "一", "个" }; 
//	int strLen1 = str1.length;// 保存第一个数组长度
//	int strLen2 = str2.length;// 保存第二个数组长度 
//	str1 = Arrays.copyOf(str1, strLen1 + strLen2);// 扩容 
//	System.arraycopy(str2, 0, str1, strLen1, strLen2);// 将第二个数组与第一个数组合并 
//	System.out.println(Arrays.toString(str1));// 输出数组 }

	/*
	 * 将九张图片遍历成数组
	 */
	@RequestMapping("jsons.do")
	public String jsons(HttpServletRequest request, HttpServletResponse response) {
		String id=request.getParameter("id");
		String username = request.getParameter("username");
//		if (username != null && username != "") {
//			List<ImgUrl> list = imgUrlService.selectlistImgUrl(username);
//			List<String> list2 = new ArrayList<String>();
//			StringBuilder sb = new StringBuilder();
//			for (int j = 0; j < list.size(); j++) {
//				String url = list.get(j).getImgurl();
//				list2.add(url);
//			}
//			if (list2.size() != 0) {
//				JSONArray jsonArray=JSONArray.fromObject(list2);
//				
//				String urlString = jsonArray.toString();
//				LianxiFood lianxiFoodsone = (LianxiFood) homePageMeiShiService
//						.selectusername(username);
//				lianxiFoodsone.setBusinessimgurl(urlString);
//				homePageMeiShiService.update(lianxiFoodsone, lianxiFoodsone);
//
//			}
//
//		} else {

			List<LianxiFood> lianxiFoods = homePageMeiShiService
					.selectUserSign();

			for (int i = 0; i < lianxiFoods.size(); i++) {
				username = lianxiFoods.get(i).getUsername();
				List<ImgUrl> list = imgUrlService.selectlistImgUrl(username);
				List<Map<String, String>> list2 = new ArrayList<Map<String, String>>();
				for (int j = 0; j < list.size(); j++) {
					Map<String, String> map = new HashMap<String, String>();
					String url = list.get(j).getImgurl();
					map.put("busiUrl", url);
					list2.add(map);
//					JSONObject jsonObject=new JSONObject();
//					jsonObject.accumulate("busiUrl", url);
				}
	
				if (list2.size() != 0) {
					JSONArray jsonArray=JSONArray.fromObject(list2);
					String urlString = jsonArray.toString();
					LianxiFood lianxiFoodsone = lianxiFoods.get(i);
					lianxiFoodsone.setBusinessimgurl(urlString);
					homePageMeiShiService
							.update(lianxiFoodsone, lianxiFoodsone);

				}
			}
//		}
		return null;

	}
}
